<script setup lang="ts">

import {message} from "ant-design-vue";
import AddCrowd from "~/contentScripts/views/wxt/BatchAddingProducts/components/AddCrowd.vue";
import {WxtBiddingConstraintType, WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";
import WxtModal from "~/contentScripts/views/wxt/wxt-modal.vue";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
  promotionScene: {
    type: String as PropType<WxtBiddingConstraintType>,
    default: WxtBiddingConstraintType.促进全店成交,
  },
  rows: {
    type: Array,
    default: () => []
  },
});
const emit = defineEmits([
  "refresh",
]);
const value = ref([]);
const visible = ref(false);
const handle = () => {
  if (props.rows.length === 0) {
    message.error('请选择要添加人群的数据');
    return;
  }
  visible.value = true;
};
const ok = () => {
  props.rows.forEach((r: any,index:number) => {
    WxtUtils.customRequest('https://one.alimama.com/crowd/batchModify.json', props.bizCode, {
      adgroupId: r.adgroupId,
      campaignId: r.campaignId,
      crowdList: value.value.map((i:any)=>{
        return {
          adgroupId: r.adgroupId,
          campaignId: r.campaignId,
          ...i,
        }
      }),
    }).then(res => {
      if (index === props.rows.length - 1) {
        message.success('添加人群成功');
        visible.value = false;
        emit('refresh');
      }
    });
  });
};
</script>

<template>
  <div @click="handle">
    <slot>
      <a-button type="primary" size="small" ghost>添加人群</a-button>
    </slot>
  </div>
  <wxt-modal title="批量添加人群" v-model:visible="visible" width="95%">
<!--    {{value}}-->
    <AddCrowd v-model:value="value" :bizCode="bizCode" :promotionScene="promotionScene" :rows="rows" :products="rows" :plans="rows" :show-bottom="false"/>
    <a-divider style="margin: 10px 0"/>
    <div style="text-align: center">
      <a-space>
        <a-button type="default" @click="visible=false">取消</a-button>
        <a-button type="primary" @click="ok">确定</a-button>
      </a-space>
    </div>
  </wxt-modal>
</template>

<style scoped>

</style>
